package com.abcgz.grade.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.abcgz.grade.dao.User;
import com.abcgz.grade.dao.UserDao;
import com.abcgz.grade.model.LoginVO;
import com.abcgz.grade.model.RestResult;

@Controller
public class IndexController {
	@Autowired
    UserDao userDao;
	
	@RequestMapping(value = "/", method = RequestMethod.GET)
    public String index() {
        return "index";
    }
	
	@RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        return "login";
    }
    
    @RequestMapping(value = "/ajaxlogin", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> ajaxlogin(@RequestBody @Valid LoginVO vo, HttpServletRequest request, HttpServletResponse response) {
    	Map<String, Object> map = new HashMap<String, Object>();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
                vo.getUsername(), vo.getPassword(), true);
        boolean flag = true;
        String msg = "";
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(usernamePasswordToken); // 完成登录
            subject.getSession().setTimeout(86400000);
            map.put("token", subject.getSession().getId());
            msg = "登陆成功！";
            map.put("flag", flag);
        } catch (Exception exception) {
            if (exception instanceof UnknownAccountException) {
                msg = "登录失败，账号或密码错误！";
            } else if (exception instanceof IncorrectCredentialsException) {
                msg = "登录失败，账号或密码错误！";
            } else {
                msg = "登录失败，发生未知错误：" + exception;
            }
            map.put("success", false);
        } finally {
            map.put("msg", msg);
            return map;
        }
    }
}
